/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-09 14:07:56
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-09 14:08:15
 * @FilePath: \goWebServer\goGameWebServer\internal\common\redis\redisHelper.go
 * @Description: 文件功能描述
 */
package redis

import (
	"context"
	"goGameWebServer/internal/common/config"
	"time"

	"github.com/gogf/gf/v2/util/gconv"
	"github.com/redis/go-redis/v9"
)

type RedisHelper struct {
	ctx         context.Context
	options     *config.RedisOptions
	RedisClient *redis.Client
}

func (this *RedisHelper) Init() {
	this.RedisClient = redis.NewClient(&redis.Options{
		Addr:     this.options.Host + ":" + gconv.String(this.options.Port),
		Password: this.options.Pass,
		DB:       this.options.DB,
	})
}

func (this *RedisHelper) Put(key string, value interface{}, expire int) error {
	return this.RedisClient.Set(this.ctx, key, value, time.Duration(expire)*time.Second).Err()
}
func (this *RedisHelper) Get(key string) (string, error) {
	return this.RedisClient.Get(this.ctx, key).Result()
}

func (this *RedisHelper) Del(key string) error {
	return this.RedisClient.Del(this.ctx, key).Err()
}
func (this *RedisHelper) Exists(key string) bool {
	return this.RedisClient.Exists(this.ctx, key).Val() > 0
}

// LLen 获取列表长度
func (this *RedisHelper) LLen(key string) (int64, error) {
	return this.RedisClient.LLen(this.ctx, key).Result()
}

// LPop 从列表左侧弹出元素
func (this *RedisHelper) LPop(key string) (string, error) {
	return this.RedisClient.LPop(this.ctx, key).Result()
}

// RPush 向列表右侧推入元素
func (this *RedisHelper) RPush(key string, values ...interface{}) (int64, error) {
	return this.RedisClient.RPush(this.ctx, key, values...).Result()
}

// Expire 设置键的过期时间
func (this *RedisHelper) Expire(key string, expiration time.Duration) error {
	return this.RedisClient.Expire(this.ctx, key, expiration).Err()
}

// LRange 获取列表指定范围的元素
func (this *RedisHelper) LRange(key string, start, stop int64) ([]string, error) {
	return this.RedisClient.LRange(this.ctx, key, start, stop).Result()
}

// LRem 从列表中删除指定值的元素
// count > 0: 从头到尾删除count个值为value的元素
// count < 0: 从尾到头删除|count|个值为value的元素  
// count = 0: 删除所有值为value的元素
func (this *RedisHelper) LRem(key string, count int64, value interface{}) (int64, error) {
	return this.RedisClient.LRem(this.ctx, key, count, value).Result()
}

func NewRedisHelper(op *config.RedisOptions) *RedisHelper {
	redisHelper := &RedisHelper{
		ctx:         context.Background(),
		options:     op,
		RedisClient: nil,
	}
	redisHelper.Init()
	return redisHelper
}
